package com.itjiange.listener;

import com.itjiange.constant.UserStatus;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import java.util.concurrent.ConcurrentMap;

/**
 * 监听 session
 *
 * @author ItJiange
 * @date 2023/10/24
 */
@WebListener
public class MySessionAttributeListener implements HttpSessionAttributeListener {
    public void attributeAdded(HttpSessionBindingEvent event) {
        System.out.println("name: " + event.getName() + "value: " + event.getValue());
        System.out.println(event.getValue());
        if (!UserStatus.USER_LOGIN_ING.equals(event.getName())) {
            return;
        }
        HttpSession session = event.getSession();
        ServletContext servletContext = session.getServletContext();
        ConcurrentMap<String, HttpSession> sessionMsg = (ConcurrentMap<String, HttpSession>) servletContext.getAttribute(UserStatus.LOGIN_ING);
        sessionMsg.put(session.getId(), session);
    }

    public void attributeRemoved(HttpSessionBindingEvent event) {
        HttpSession session = event.getSession();
        System.out.println("session id : " + session.getId());
        ServletContext servletContext = session.getServletContext();
        ConcurrentMap<String, HttpSession> sessionMsg = (ConcurrentMap<String, HttpSession>) servletContext.getAttribute(UserStatus.LOGIN_ING);
        sessionMsg.remove(session.getId());
    }
}
